<template>
    <div class="updateStockMasterTask">
        <div class="publicSearch bigFormBox3">
            <div class="searchBar" :style="{height: isMoreSearch?'auto':''}">
                <p style="font-size: 20px;font-weight: 600;line-height: 20px;margin: 15px 0;">新增盘点任务</p>
                <el-form class="clearFloat"  :model="form" :rules="rules" ref="form">
                    <el-form-item label="仓库" prop="wareId" :label-width="formLabelWidth">
                        <el-select  @change = "onChangeWare"  v-model="wareName" size="mini">
                            <el-option  v-for="item in wares"
                                        :key="item.wareId"
                                        :label="item.wareName"
                                        :value="item.wareId"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="类型" prop="type" :label-width="formLabelWidth">
                        <el-select v-model="form.type" @change="changeType" filterable placeholder="请选择类型" size="small"
                                   style="width: 100%;">
                            <el-option
                                    v-for="item in stockTaskMasterType"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="showChoose" label="选择库位" :label-width="formLabelWidth">
                        <el-input  size="small"
                                :title="form.cellCodes" v-model="form.cellCodes" placeholder="请选择库位" style="width:80%;" readonly></el-input>
                        <el-button @click="showSelectItemModal" icon="iconfont icon-jia" type="text"
                                   style="width: 10%;" ></el-button>
                    </el-form-item>
                    <!--<div style="float:left;width:100%;"></div>
                    <el-form-item label="是否随机" prop="checkWare" :label-width="formLabelWidth"
                                  class="checkItemBoxHeight">
                        <el-checkbox v-model="form.ifRandom" :true-label="1" :false-label="0">随机盘点</el-checkbox>
                    </el-form-item>-->
                    <el-form-item v-show="showNum" label="抽盘个数" :label-width="formLabelWidth">
                        <el-input v-model="form.randomNum" placeholder="请输入任务数" size="small"></el-input>
                    </el-form-item>
                    <div style="float: left;width: 100%;">
                        <el-divider content-position="left">盘点开始时间</el-divider>
                    </div>
                    <el-form-item label="开始时间" prop="dynamicFromTime" :label-width="formLabelWidth">
                        <el-date-picker
                                v-model="form.dynamicFromTime"
                                type="datetime"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                size="small"
                                placeholder="请选择盘点开始时间">
                        </el-date-picker>
                    </el-form-item>
                </el-form>
            </div>
            <!--      <span class="moreSearchBtn"-->
            <!--            :class="isMoreSearch?'el-icon-caret-top':'el-icon-caret-bottom'"-->
            <!--            @click="isMoreSearch = !isMoreSearch"></span>-->
        </div>
        <el-dialog width="800px" title="选择库位" :visible.sync="innerVisibleItem" append-to-body style="margin-top: -10vh;">

            <div class="publicSearch body">
                <div class="searchBar" :style="{height: isMoreSearch2?'auto':''}">
                    <el-button-group>
                        <el-button @click="getItemData" size="mini" icon="el-icon-search">查询</el-button>
                        <el-button @click="clearSearchSelectItem" size="mini" icon="el-icon-refresh">重置</el-button>
                    </el-button-group>
                    <div>
                        <span>货位编码</span>
                        <el-input v-model="searchSelectItem.cellCode" size="mini" placeholder="请输入货位编码"
                                  clearable></el-input>
                    </div>
                    <div>
                        <span>物料</span>
                        <el-input v-model="searchSelectItem.keyWords" size="mini" placeholder="物料编码/物料名称"
                                  clearable></el-input>
                    </div>
                </div>
                <span class="moreSearchBtn"
                      :class="isMoreSearch2?'el-icon-caret-top':'el-icon-caret-bottom'"
                      @click="isMoreSearch2 = !isMoreSearch2"></span>
            </div>

            <div style="height: 400px" class="">
                <el-table
                        max-height="460"
                        :data="items"
                        :row-key="bindRowKeys"
                        @selection-change="handleSelectionChange"
                        style="width: 100%;">
                    <el-table-column
                            fixed="left"
                            :reserve-selection="true"
                            type="selection"
                            width="50">
                    </el-table-column>
                    <el-table-column
                            sortable
                            show-overflow-tooltip
                            fixed="left"
                            prop="cellName"
                            label="货位名称"
                           >
                    </el-table-column>
                    <el-table-column
                            sortable
                            show-overflow-tooltip
                            prop="cellCode"
                            label="货位编码"
                            >
                    </el-table-column>

                </el-table>
                <el-pagination
                        style="text-align: right;"
                        @current-change="handleCurrentChange2"
                        :current-page.sync="searchSelectItem.pageNum"
                        :page-size="searchSelectItem.pageSize"
                        layout="total, prev, pager, next, jumper"
                        :total="searchSelectItem.total">
                </el-pagination>
            </div>
            <div>
                <el-button @click="sure" style="background-color: #00a5d2;color: white" size="mini" >确认</el-button>
            </div>
        </el-dialog>

        <div class="createFootBox clearFloat"
             :style="{width: isCollapse ? 'calc(100% - 104px)' : 'calc(100% - 240px)'}">
            <div class="leftFloat">
                <el-button type="info" @click="$router.push({name: 'stockTakeMaster'})">返 回</el-button>
            </div>
            <div class="rightFloat">
                <el-button @click="commitForm('form')" type="primary">提 交</el-button>
            </div>
        </div>

    </div>
</template>

<script>
    import {mapState} from "vuex";

    export default {
        name: 'createStockMasterTask',
        data() {
            return {
                //bindRowKeys:'',
                chooseResult:[],
                showChoose:false,
                showNum:true,
                formLabelWidth: '120px',
                wares: [],
                wareCode:'',
                wareName:'',
                wareId:'',
                organizations: [],
                areas: [],
                areastwo: [],
                shelfs:[],
                shelfstwo:[],
                cells:[],
                cellstwo:[],

                suppliers: [],

                form: {
                    type: 1,
                    wareId: '',
                    wareName: '',
                    itemCode: '',
                    cellCodes:'',
                    dynamicFromTime: '',
                    randomNum: '',
                },

                isMoreSearch: true,
                isMoreSearch2: true,
                searchData: {
                    pageNum: 1,
                    pageSize: 10,
                    total: null,
                    keyWords: '',
                    wareId: PF.getLocal('wareId', 'number'),
                    organizationId: null,

                },
                searchSelectItem: {
                    pageNum: 1,
                    pageSize: 5,
                    wareId: '',
                    total: null,
                    keyWords: '',
                    cellCode:'',
                    isEmpty:null,
                    itemTypeId: '',
                    supplierId: '',
                    organizationId: '',
                },
                innerVisibleItem: false,
                items:[],
                itemTypeTree:[],
                packDetails:[],
                batchTactics:[],

                rules: {
                    dynamicFromTime: [{required: true, message: '请选择时间', trigger: 'blur'}],
                   /* wareId: [{required: true, message: '请选择仓库', trigger: 'blur'}],
                    type: [{required: true, message: '请选择类型', trigger: 'blur'}],
                    priority: [{required: true, message: '请选择优先级', trigger: 'blur'}],
                    /!*organizationId: [{required: true, message: '请选择货主', trigger: 'blur'}],*!/
                    itemCode: [{required: true, message: '请输入物料编码', trigger: 'blur'}],
                    fromAreaCode: [{required: true, message: '请选择货区', trigger: 'blur'}],
                    toAreaCode: [{required: true, message: '请选择货区', trigger: 'blur'}],
                    dynamicFromTime: [{required: true, message: '请选择时间', trigger: 'blur'}],
                    fromShelfCode: [{required: true, message: '请输入从货架区编码', trigger: 'blur'}],
                    toShelfCode: [{required: true, message: '请输入至货架区编码', trigger: 'blur'}],
                    itemKeywords: [{required: true, message: '请输入产品编码', trigger: 'blur'}],
                    fromCellCode: [{required: true, message: '请输入从货位', trigger: 'blur'}],
                    toCellCode: [{required: true, message: '请输入至货位', trigger: 'blur'}],
                    boxCode: [{required: true, message: '请输入追踪号', trigger: 'blur'}],*/
                }
            }
        },
        computed: {
            ...mapState([
                "stockTaskMasterType",
                "stockTaskMasterOrder"
            ]),
            isCollapse() {
                return this.$parent.leftMenuIsCollapse;
            },
        },
        watch: {},
        methods: {
            handleSelectionChange(val) {
                this.chooseResult = val;
                console.log("选择项：",this.chooseResult)
            },
            bindRowKeys(row){
                return row.cellId;
            },
            changeType(val){
                if (val == 1){
                    this.showNum = true;
                    this.showChoose = false;
                } else if (val == 2){
                    this.showNum = false;
                    this.showChoose = true;
                } else {
                    this.showNum = false;
                    this.showChoose = false;
                }
            },
            showSelectItemModal() {
                if (!PF.isNull(this.searchSelectItem.wareId)) {
                    IOT.tips('未选择仓库！', 'error');
                    return false;
                }
                this.form.cellCodes = '';
                this.searchSelectItem.organizationId = this.form.organizationId;
                this.getItemData();
                this.getItemTypeData();
                this.innerVisibleItem = true;
            },
            getItemData() {
                let searchSelectItem = JSON.parse(JSON.stringify(this.searchSelectItem))
                IOT.getServerData('/cell/infos/cellByWareIdlist', 'get', searchSelectItem, (ret) => {
                    console.log("查询货位返回：",ret)
                    if (ret.code === 200) {
                        this.items = ret.rows;
                        this.searchSelectItem.total = ret.total;
                        this.searchSelectItem.pageNum = ret.pageNumber
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },
            getItemTypeData() {
                IOT.getServerData('/item/types/list', 'get', {}, (ret) => {
                    if (ret.code === 200) {
                        let list = ret.rows;
                        for (let i = 0; i < list.length; i++) {
                            list[i].value = list[i].itemTypeId;
                            list[i].id = list[i].itemTypeId;
                            list[i].label = list[i].itemTypeName;
                        }
                        // this.itemTypes = list;
                        this.itemTypeTree = PF.toTree(list);
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },
            onChangeWare(val){
                //console.log("选择了:",val)
                this.searchSelectItem.wareId = val;
                this.form.wareId = val;
                this.wareId = val;
                this.wareCode = this.wares[this.wares.findIndex(item =>{
                    return item.wareId == val;
                })].wareCode;
                this.form.wareName = this.wares[this.wares.findIndex(item =>{
                    return item.wareId == val;
                })].wareName;
                console.log("选择了:",this.wareCode)
            },
            clearSearchSelectItem() {
                this.searchSelectItem.keyWords = '';
                this.searchSelectItem.itemTypeId = '';
                this.searchSelectItem.supplierId = '';
                this.searchSelectItem.organizationId = '';
                this.searchSelectItem.cellCode = ''
            },
            handleCurrentChange2(val) {
                this.searchSelectItem.pageNum = val;
                this.getItemData()
            },
            sure(){
                console.log("选择的货位：",this.chooseResult)
                if (this.chooseResult.length>0){
                    this.chooseResult.forEach(item =>{
                        this.form.cellCodes += item.cellCode + ","
                    })
                    this.innerVisibleItem = false;
                }else {
                    IOT.tips('请至少选择一个库位！', 'error');
                }
                if (this.form.cellCodes) {
                    this.form.cellCodes = this.form.cellCodes.substring(0,this.form.cellCodes.length-1);
                }
            },
            selectItem(row) {
                this.form.itemCode = row.itemCode;
                this.getPackDetailData(row.packCode);
                this.getBatchTacticData(row.batchTacticCode);
                this.innerVisibleItem = false;
            },
            getPackDetailData(packCode) {
                IOT.getServerData('/pack/details/list', 'get', {packCode: packCode}, (ret) => {
                    if (ret.code === 200) {
                        this.packDetails = ret.rows;
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },
            getBatchTacticData(batchTacticCode) {
                if(batchTacticCode==null || batchTacticCode==''){
                    batchTacticCode = this.batchTacticCode;
                }
                IOT.getServerData('/batch/tactics/findByBatchTacticCode', 'get', {
                    batchTacticCode:batchTacticCode
                }, (ret) => {
                    if (ret.code === 200) {
                        let list = PF.JSON(ret.rows[0])
                        let detailDetails = list.batchTacticDetailDetails;
                        let testDetailDetails = [];
                        list.batchTacticDetails[12].values = [];
                        list.batchTacticDetails[13].values = [];
                        for (let i = 0; i < detailDetails.length; i++) {
                            if (detailDetails[i].detailCode === 'batchAttribute1') {
                                // testDetailDetails.push(detailDetails[i])
                                list.batchTacticDetails[12].values.push(detailDetails[i])
                            } else if (detailDetails[i].detailCode === 'batchAttribute2') {
                                list.batchTacticDetails[13].values.push(detailDetails[i])
                            }
                        }

                        let batchTacticDetails = list.batchTacticDetails;
                        let testBatchTacticDetails = [];
                        for (let i = 0; i < batchTacticDetails.length; i++) {
                            if (batchTacticDetails[i].state === 1) {
                                testBatchTacticDetails.push(batchTacticDetails[i])
                                if (batchTacticDetails[i].isRequired === 1) {
                                    this.rules[batchTacticDetails[i].detailCode][0].required = true;
                                }
                                if (batchTacticDetails[i].detailCode === 'inDate') {
                                    this.form[batchTacticDetails[i].detailCode] = PF.getNowFormatDate();
                                }
                            }
                        }

                        list.batchTacticDetailDetails = testDetailDetails;
                        list.batchTacticDetails = testBatchTacticDetails;
                        this.batchTactics = list;
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },

            getAreaData() {
                IOT.getServerData('/area/infos/list', 'get', {wareId: this.form.wareId}, (ret) => {
                    if (ret.code === 200) {
                        this.areas = ret.rows;
                        this.areastwo = ret.rows;
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },

            getShelf(row){
                let that = this;
                let areaCode = '';
                if(row === 1){
                    areaCode = that.form.fromAreaCode;
                    that.form.fromShelfCode = '';
                    that.form.fromCellCode = '';
                }else{
                    areaCode = that.form.toAreaCode;
                    that.form.toShelfCode = '';
                    that.form.toCellCode = '';
                }
                IOT.getServerData('/shelf/infos/list', 'get', {areaCode:areaCode}, (ret) => {
                    if (ret.code === 200) {
                        if(row === 1){
                            that.shelfs = ret.rows;
                        }else{
                            that.shelfstwo = ret.rows;
                        }
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },
            getWareData(){
                IOT.getServerData('/ware/infos/list','get',{},(ret) => {
                    if (ret.code === 200) {
                        this.wares = ret.rows;
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },

            getCell(row) {
                let that = this;
                let shelfCode = '';
                if(row === 1) {
                    shelfCode = that.form.fromShelfCode;
                    that.form.fromCellCode = '';
                }else{
                    shelfCode = that.form.toShelfCode;
                    that.form.toCellCode = '';
                }
                IOT.getServerData('/cell/infos/list', 'get', {shelfCode:shelfCode}, (ret) => {
                    if (ret.code === 200) {
                        if(row === 1)
                            that.cells = ret.rows;
                        else{
                            that.cellstwo = ret.rows;
                        }
                    } else {
                        IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                    }
                });
            },

            commitForm(formName) {
                IOT.showOverlay('保存中，请稍等...');
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        IOT.showOverlay('保存中，请稍等...');
                        let form = PF.JSON(this.form);
                        /*for (let i = 0; i < this.organizations.length; i++) {
                            if (this.organizations[i].organizationId === form.organizationId) {
                                form.organizationName = this.organizations[i].organizationName;
                                break
                            }
                        }
                        for(let i=0;i<this.wares.length;i++){
                            if(this.wares[i].wareId === form.wareId){
                                form.wareName = this.wares[i].wareName;
                                form.wareCode = this.wares[i].wareCode;
                                break
                            }
                        }*/
                        if (form.type == 1 && !PF.isNull(form.randomNum)) {
                            IOT.tips('随机盘点请填写随机生成的任务数！', 'error', 1000, () => {
                                IOT.hideOverlay();
                            });
                            return false
                        }
                        if (form.type == 2 && !PF.isNull(form.cellCodes)) {
                            IOT.tips('指定货位盘点请至少选择1个货位！', 'error', 1000, () => {
                                IOT.hideOverlay();
                            });
                            return false
                        }
                        let params = {
                            stockTakeMaster: form,
                        }
                        console.log("保存参数：",params)
                        IOT.hideOverlay();
                        IOT.getServerData('/stock/take/masters/insert', 'post', params, (ret) => {
                            IOT.hideOverlay();
                            if (ret.code === 200) {
                                IOT.tips('保存成功！', 'success');
                                this.searchSelectItem.wareId = null;
                                this.form.wareId = null;
                                this.form.wareName = '';
                                this.$router.push({name: 'stockTakeMaster'})
                            } else {
                                IOT.tips(ret.message || '服务器请求失败，稍后再试！', 'error');
                            }
                        });
                    } else {
                        IOT.hideOverlay();
                        console.error('error submit!!');
                        return false;
                    }
                });
            },

            clearForm: function () {
                this.form = {
                    type: 1,
                    state: 0,
                    priority: 1,
                    wareId: PF.getLocal('wareId', 'number'),
                    wareName: '',
                    wareCode: '',
                    organizationId: '',
                    organizationName: '',
                    itemCode: '',
                    fromAreaCode: '',
                    toAreaCode: '',
                    dynamicFromTime: '',
                    fromShelfCode: '',
                    toShelfCode: '',
                    itemKeywords: '',
                    fromCellCode: '',
                    toCellCode: '',
                    boxCode: '',
                    udfHs1: '',
                    udfHs2: '',
                    udfHs3: '',
                    ifRandom: 0,
                    randomNum: '',
                }
            }
        },
        created() {
            PF.getOrganizations((rows) => {
                this.organizations = rows;
            });
            //this.getAreaData();
            this.getWareData();
            PF.getSuppliers((rows) => {
                this.suppliers = rows;
            });
        },
        mounted() {
        }
    }
</script>

<style scoped lang="less">
    .createBuyBillIn {
        padding-bottom: 100px;
    }
</style>
